package org.example.atry.myservlet;

import jakarta.servlet.GenericServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.atry.service.impl.serviced;
import org.example.atry.service.agricultuerservicec;
import org.example.atry.util.Users;
import org.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/queryone")
public class queryone extends GenericServlet {
    @Override

    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 设置允许跨域的头部信息
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");



       String ser=request.getParameter("chaxun");
//        System.out.println(ser);
        //int cat=Integer.parseInt(ser);
        //System.out.println(cat);
        agricultuerservicec serviced=new serviced();
        //获取session传递的信息HttpSession session = request.getSession();
        //String set = (String) session.getAttribute("chaxun");
        int caa=Integer.parseInt(ser);
        //System.out.println(caa);
        Users ca=serviced.queryone(caa);

// 设置响应内容类型为 JSON
        response.setContentType("application/json;charset=UTF-8");
            JSONObject as = new JSONObject();
            as.put("caa",ca);
            //System.out.println(ca);
            PrintWriter out = response.getWriter();
            out.print(as.toString());
            out.flush();



      //用servlet返回json数据时，不要设定页面跳转到前端，否则无法返回数据。
        // 是前端对他进行请求，然后它返回数据，不是它带着数据跳转到前端页面，前端再进行请求。
        // 如果这么做了，前端在发起请求时，他就会跳转页面，导致axios出错，访问混乱
        // request.getRequestDispatcher("queryone.html").forward(request, response);
/*
        request.setAttribute("ca", ca);
        request.getRequestDispatcher("queryone.jsp").forward(request, response);
        request.getSession().invalidate();

 */

    }
}
